# task_master.py
import platform

# 从BaseManager继承的QueueManager:
import time

import facade
from xjlibrary.mprocesspoll.process_distributed.BaseTask import BaseTask
from xjlibrary.network.MyIP import get_local_ip, GetLocalIPByPrefix
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class SendTask(BaseTask):
    def __init__(self):
        super().__init__()
        sysstr = platform.system()
        if sysstr == "Windows":
            self.ip = GetLocalIPByPrefix("192.168.")
        else:
            self.ip = get_local_ip("enp2s0")
        self.port = 5000
        self.init_send(self.ip, self.port)


class SelectTask(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=self.logger)

    def selectDB(self):
        sql = "select standardid from articlenew where stat=0 and failcount <3 limit 50000"
        # sql = "select wanID from article1 where stat=0 and failcount <3 limit 50000"
        rows = self.mysqlutils.SelectFromDB(sql)
        return rows


if __name__ == "__main__":
    sendtask = SendTask()
    select = SelectTask()
    sendtask.start()
    sendtask.set_task_result_obj()
    while True:
        if sendtask.task.qsize() != 0:
            print("send task num is:" + str(sendtask.task.qsize()))
        else:
            rows = select.selectDB()
            if rows:
                try:
                    for row in rows:
                        sendtask.set_task(row[0], block=False)
                except:
                    print("队列已满 处理结果队列")
            time.sleep(60)

        if sendtask.result.qsize() != 0:
            print("result num is:" + str(sendtask.result.qsize()))
            truelist = []
            falselist = []
            for i in range(1, sendtask.result.qsize() + 1):
                result = sendtask.result.get()
                if result[1] == 1:
                    truelist.append(result[0])
                else:
                    falselist.append(result[0])
            if truelist:
                if len(truelist) == 1:
                    truelist.append("test")
                sql = "update articlenew set stat=1 where standardid in {}".format(tuple(truelist))
                # sql = "update article1 set stat=1 where wanID in {}".format(tuple(truelist))
                select.mysqlutils.ExeSqlToDB(sql)
            if falselist:
                if len(falselist) == 1:
                    falselist.append("test")
                sql = "update articlenew set failcount=failcount+1 where standardid in {}".format(tuple(falselist))
                # sql = "update article1 set failcount=failcount+1 where wanID in {}".format(tuple(falselist))
                select.mysqlutils.ExeSqlToDB(sql)
